import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {BaseTreeService} from '@sb/base/core/service/base-tree.service';
import {OuOrgService} from '../ou-org-user/service/ou-org.service';
import {BaseNzTreeNodeOptions, BaseTreeComponent, Page, ReturnForm} from '@sb/base';
import {OuOrgSearchConfig} from '../ou-org-user/entity/ou-org-search-config';
import {Observable} from 'rxjs';
import {NzTreeNode} from 'ng-zorro-antd/core/tree/nz-tree-base-node';
import {SsoService} from '../../../main/service/sso.service';
import {STData} from '@delon/abc';
import {map, max} from 'rxjs/operators';

@Component({
    selector: 'ou-org-user-tree-select-panel',
    templateUrl: './ou-org-user-tree-select-panel.component.html',
    providers: [{
        provide: BaseTreeService,
        useClass: OuOrgService
    }]
})
export class OuOrgUserTreeSelectPanelComponent implements OnInit {

    @ViewChild('baseTree', {static: false})
    baseTree: BaseTreeComponent;

    @Input()
    showSearch = false;

    showRoot = false;

    rootNodeId = '-1';

    init = false;

    typeIcon = {
        root: 'dr:hy-root',
        ORG: 'dr:hy-module',
        DEPT: 'dr:hy-terminal',
        USER: 'dr:user_yw'
    };

    @Output()
    selectNode = new EventEmitter<NzTreeNode>();

    @Input()
    searchConfig: OuOrgSearchConfig;

    @Input()
    checkable: boolean;

    constructor(private ssoService: SsoService) {

    }

    ngOnInit(): void {
        this.ssoService.checkAdmin().subscribe(
            res => {
                this.showRoot = res.success;
                this.init = true;
            }
        );
    }

    onSelectNode(selectedNodeTreeNode: NzTreeNode): void {
        this.selectNode.emit(selectedNodeTreeNode);
    }

    reload(): Observable<any> {
        return this.baseTree.reload();
    }

    reloadNode(nodeId) {
        this.baseTree.reloadNode(nodeId);
    }

    loadTree(parentId: string, searchConfig: any, maxLevel: number, baseTreeService: BaseTreeService<STData, Page, BaseNzTreeNodeOptions<STData>>): Observable<ReturnForm<BaseNzTreeNodeOptions<any>[]>> {
        return baseTreeService.getNzTree(parentId, searchConfig, maxLevel).pipe(
            map(
                res => {
                    if (res.success) {
                        if (!this.showRoot) {
                            this.rootNodeId = res.message[0].key;
                        }
                    }
                    return res;
                }
            )
        );
    }
}
